import axios from 'axios';
import type {AxiosResponse } from 'axios'
const api = "/api";
import { ElNotification } from 'element-plus'
//构建一个 axios 实例
export const axiosInstance = axios.create({
	baseURL: api,
	timeout: 60000,
});

/**
 * 定义业务应答格式
 */
export interface Resonse<T> {
	//业务代码 0 表示成功
	code: string;
	//业务代码描述
	message: string;
	//业务数据
	data: T;
}

export interface PageResonse<T> {
	//业务代码 0 表示成功
	code: string;
	//业务代码描述
	message: string;
	//业务数据
	data: Page<T>;
}

export interface Page<T> {
	count: number;
	customData: any;
	dataList: T[];
	pageCount: number;
	pageNo: number;
	pageSize: number;
}
export class PageQuery {
     pageNo: number = 1;
     pageSize: number = 10;
    orderField: String = "";
     orderType: String = "";
    constructor() {};
}

// 请求拦截器，追加 token
axiosInstance.interceptors.request.use((config) => {
	const token = localStorage.getItem("Authorization");
	if (token != null) {
		config.headers["Authorization"] = token;
	}
	return config;
}, function (error) {
	return Promise.reject(error);
});

//应答拦截器，拦截网络失败和业务失败
axiosInstance.interceptors.response.use(
	// 请求成功
	(res: AxiosResponse<Resonse<unknown>>) => {
		console.log("axiosInstance.interceptors.response 操作成功", res.data);
		if (res.data.code !== "0") {
			ElNotification({message: res.data.message,type: 'error'});
		}
		return res;
	},
	// 请求失败
	error => {
		switch (error.response?.status) {
			case 400:
				error.message = '请求错误(400)';
				break;
			case 401:
				error.message = '未授权(401)';
				break;
			case 403:
				error.message = '拒绝访问(403)';
				break;
			case 404:
				error.message = '请求资源不存在(404)';
				break;
			case 405:
				error.message = '请求方式错误(405)';
				break;
			case 500:
				error.message = '服务器错误(500)';
				break;
			default:
				error.message = `连接出错(${error.response?.status})!`;
		}
		ElNotification.error(error.message);
		return Promise.reject(error);
	}
);

//应答处理，处理 null 的情况
export function handleResponse<T>(res: Resonse<T> | any) {
	console.log("handleResponse", res)
	return res.data == null ? {} : res.data;
}


export function handlePageResponse<T>(res: PageResonse<T>) :PageResonse<T>{
	console.log("handleResponse", res)
	// if(!res){
	// 	res = {};
	// }
	let data = res.data;
	// if(!data){
	// 	data = {count:0,pageCount:0,pageNo:1,pageSize:15};
	// }
	if (!data.dataList == null) {
		data.dataList = [];
	}
	if (data.count == null) {
		data.count = 0;
	}
	if (data.pageCount == null) {
		data.pageCount = 0;
	}
	if (data.pageNo == null) {
		data.pageNo = 1;
	}
	if (data.pageSize == null) {
		data.pageSize = 15;
	}
	res.data = data;
	return res;
}